﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CarErp.Model;
using CarErp.Data;

namespace CarErp.Forms
{
	public partial class ApplicationViewForm : Form
	{
		public ApplicationViewForm()
		{ }

		public ApplicationViewForm(CarERPContext context, User user)
		{
			InitializeComponent();
			Context = context;
			User = user;

			var allCompanys = context.CarPurchaseApplications.Select(x => x.ApplicantCompany).ToArray();
			carPurchaseApplicationFilter.SetCompanys(allCompanys);

			DisableFilter();
		}

		private void listBar_ItemSelected(int id)
		{
			var app = Context.CarPurchaseApplications.Find(id);
			this.carPurchaseApplicationView.SetModel(app);
			Current = app;

			if (app.ApprovalPaper == null)
			{
				carPurchaseApprovalView.Reset();
				button_Approve.Enabled = true;
			}
			else
			{
				carPurchaseApprovalView.SetModel(app.ApprovalPaper);
				button_Approve.Enabled = false;
			}
		}

		private void button_Filter_Click(object sender, EventArgs e) => FilterBehavior();

		private Action FilterBehavior;

		private void EnableFilter()
		{
			button_Filter.Text = "解除筛选";
			UsingFilter(carPurchaseApplicationFilter.Filter);
			FilterBehavior = DisableFilter;
		}

		private void DisableFilter()
		{
			button_Filter.Text = "启用筛选";
			UsingFilter(_ => true);
			FilterBehavior = EnableFilter;
		}

		private void UsingFilter(Expression<Func<CarPurchaseApplication, bool>> filter)
		{
			var ids = Context.CarPurchaseApplications.Where(filter).Select(x => x.Id).ToArray();
			if (!ids.Any())
			{
				MessageBox.Show("无可奉告");
				DisableFilter();
				return;
			}
			listBar.SetItems(ids);
		}

		private void button_Approve_Click(object sender, EventArgs e)
		{
			using (var approvelForm = new ApprovelForm(User))
			{
				approvelForm.OnApproved += approvel =>
				 {
					 Current.ApprovalPaper = approvel;
					 Context.SaveChanges();
					 approvelForm.Close();
				 };

				approvelForm.ShowDialog();
			}

			listBar_ItemSelected(Current.Id);
		}

		private CarPurchaseApplication Current;
		private readonly CarERPContext Context;
		private readonly User User;
	}
}
